﻿using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.Text;

namespace WpfApp1.tools
{
    class DBConnection
    {
        MySqlConnection connection;
        public  DBConnection()
        {
            try
            {
                string MyConStr = "Server=localhost;Database=web;uid=root;pwd=123456";
                // 连接数据库
                connection = new MySqlConnection(MyConStr);
            }
            catch (Exception exception)
            {
                throw new Exception("DBConnection Constructor:" + exception.Message);
            }
        }

        public DataTable Select(String sqlStr)
        {
            try
            {
                // 打开数据库
                connection.Open();
                Console.WriteLine("---开始查询--");
                MySqlCommand sqlCmd = new MySqlCommand(sqlStr, connection);
                MySqlDataAdapter sda = new MySqlDataAdapter(sqlCmd);

                DataTable ds = new DataTable();
                sda.Fill(ds);
                return ds;
            }
            catch (Exception exception)
            {
                throw new Exception("SelectMethod:" + exception.Message);
            }
            finally
            {
                // 关闭数据库
                connection.Close();
            }
        }
    }
}
